package com.gs.SynPatrolRep.util;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.gs.SynPatrolRep.MyApplication;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

public class ImageUtil {
    private static volatile ImageUtil instance;

    public ImageUtil() {
    }

    public static ImageUtil getInstance() {
        if (instance == null) {
            synchronized (ImageUtil.class) {
                if (instance == null) {
                    instance = new ImageUtil();
                }
            }
        }
        return instance;
    }

    public void loadImg(Context activity, String url, ImageView iv) {
        Glide.with(activity)
                .load(url)
                .into(iv);
    }

    public void loadBitmap(Activity activity, Bitmap bitmap, ImageView iv) {
        if (ActivityUtil.getInstance().isSurvive(activity)) {
            Glide.with(activity)
                    .load(bitmap)
                    .into(iv);
        }
    }

    /**
     * 刷新圖片，不使用緩存
     *
     * @param activity
     * @param url
     * @param iv
     */
    public void loadImgWithout(Activity activity, String url, ImageView iv) {
        if (ActivityUtil.getInstance().isSurvive(activity)) {
            Glide.with(activity)
                    .load(url)
                    .skipMemoryCache(true)
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .into(iv);
        }
    }

    public void getBitmap(Context context, String imgUrl, Handler handler, int arg) {
        Glide.with(context)
                .asBitmap()
                .load(imgUrl)
                .into(new CustomTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        Message message = Message.obtain();
                        message.what = 1;
                        message.arg1 = arg;
                        message.obj = resource;
                        handler.sendMessage(message);
                    }

                    @Override
                    public void onLoadCleared(@Nullable Drawable placeholder) {

                    }
                });
    }

    public String bitmapToUrl(Context context, Bitmap bitmap) {
        FileOutputStream fops = null;
        String path = "";
        File saveFile = FileUtils.getInstance().createFile(context, "hkpc" + DateUtil.getInstance().DateTimeToStr(new Date(), "yyyyMMdd_hhmmss") + ".jpg");
        path = saveFile.getAbsolutePath();
        try {
            fops = new FileOutputStream(path);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fops);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fops != null) {
                    fops.flush();
                    fops.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return path;
    }

    public Bitmap resizeBitmap(Bitmap bitmap) {
        Bitmap resizeBmp = null;
        if (bitmap != null) {
            DisplayMetrics dm = MyApplication.getContext().getResources().getDisplayMetrics();
            int newWidth = dm.widthPixels;
            int width = bitmap.getWidth();
            float scale = ((float) newWidth) / width;
            Matrix matrix = new Matrix();
            matrix.postScale(scale, scale);
            resizeBmp = Bitmap.createBitmap(bitmap, 0, 0, width, bitmap.getHeight(), matrix, true);
        }
        return resizeBmp;
    }

    public Bitmap resizeImage(String srcPath) {
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        //开始读入图片，此时把options.inJustDecodeBounds 设回true了
        newOpts.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);//此时返回bm为空

        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        //现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
        float hh = 800f;//这里设置高度为800f
        float ww = 480f;//这里设置宽度为480f
        //缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        int be = 1;//be=1表示不缩放
        if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
            be = (int) (newOpts.outWidth / ww);
        } else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
            be = (int) (newOpts.outHeight / hh);
        }
        if (be <= 0)
            be = 1;
        newOpts.inSampleSize = be;//设置缩放比例
        //重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
        bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
        return compressImage(bitmap);//压缩好比例大小后再进行质量压缩
    }

    private Bitmap compressImage(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        int options = 90;
        int length = baos.toByteArray().length / 1024;

        if (length > 5000) {
            //重置baos即清空baos
            baos.reset();
            //质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
            image.compress(Bitmap.CompressFormat.JPEG, 10, baos);
        } else if (length > 4000) {
            baos.reset();
            image.compress(Bitmap.CompressFormat.JPEG, 20, baos);
        } else if (length > 3000) {
            baos.reset();
            image.compress(Bitmap.CompressFormat.JPEG, 50, baos);
        } else if (length > 2000) {
            baos.reset();
            image.compress(Bitmap.CompressFormat.JPEG, 70, baos);
        }
        //循环判断如果压缩后图片是否大于1M,大于继续压缩
        while (baos.toByteArray().length / 1024 > 1024) {
            //重置baos即清空baos
            baos.reset();
            //这里压缩options%，把压缩后的数据存放到baos中
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);
            //每次都减少10
            options -= 10;
        }
        //把压缩后的数据baos存放到ByteArrayInputStream中
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
        //把ByteArrayInputStream数据生成图片
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);
        return bitmap;
    }
}
